from base.base import Base
from selenium.webdriver.common.by import By
from time import sleep


class KeywordPage(Base):
    # 页面元素定位
    __menu_mall = (By.XPATH, '//span[text()="商场管理"]')
    __menu_keyword = (By.XPATH, '//span[text()="关键词"]')
    __text_first_keyword = (By.XPATH, '//table[@class="el-table__body"]/tbody/tr[1]/td[2]/div')
    __btn_delete = (By.XPATH, '//table[@class="el-table__body"]/tbody/tr[1]/td[6]/div/button[2]')

    # 成功消息定位 - 根据截图中的元素
    __success_notification = (By.CLASS_NAME, 'el-notification')  # 通知容器
    __success_message = (
    By.XPATH, '//div[contains(@class, "el-notification")]//p[contains(text(), "删除成功")]')  # 成功消息文本
    __success_message_alt = (By.XPATH, '//div[contains(@class, "el-notification")]//p')  # 备用消息定位

    def delete_first_keyword(self) -> tuple:
        """
        删除第一个关键词业务流程
        返回: (删除前的关键词名称, 成功消息文本)
        """
        try:
            # 1. 点击商场管理菜单
            self.loc_wait_ele(self.__menu_mall).click()
            sleep(1)

            # 2. 点击关键词子菜单
            self.loc_wait_ele(self.__menu_keyword).click()
            sleep(2)

            # 3. 记录删除前的关键词名称
            delete_keyword = self.loc_wait_ele(self.__text_first_keyword).text
            print(f"将要删除的关键词: {delete_keyword}")

            # 4. 点击删除按钮
            self.loc_wait_ele(self.__btn_delete).click()
            print("已点击删除按钮")

            # 5. 等待成功消息出现
            sleep(2)
            success_message = self.get_success_message()

            return delete_keyword, success_message

        except Exception as e:
            print(f"删除流程异常: {str(e)}")
            return "", ""

    def get_success_message(self) -> str:
        """获取成功消息文本"""
        try:
            # 等待通知容器出现
            self.loc_wait_ele(self.__success_notification, timeout=5)
            print("成功通知容器已出现")

            # 方案1: 精确匹配"删除成功"
            message = self.loc_wait_ele(self.__success_message, timeout=3).text
            print(f"获取到成功消息: {message}")
            return message
        except:
            try:
                # 方案2: 获取通知中的第一个p标签文本
                message = self.loc_wait_ele(self.__success_message_alt, timeout=3).text
                print(f"获取到消息文本: {message}")
                return message
            except:
                print("未找到成功消息")
                return ""

    def is_delete_successful(self) -> bool:
        """检查删除是否成功（基于成功消息）"""
        try:
            message = self.get_success_message()
            return "删除成功" in message or "成功" in message
        except:
            return False